package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisTools;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTools redisTools;

    @Override
    public Result queryById(Long id) {

        //缓存穿透
        //Shop shop = redisTools.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //缓存穿透
        Shop shop = redisTools.queryWithPassThrough(id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop==null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }






     //缓存穿透
//    @Override
//    public Shop queryWithPassThrough(Long id) {
//        String key="cache:shop" + id;
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        //判断缓存数据是否不为空
//        if (StrUtil.isNotBlank(shopJson)){
//            return JSONUtil.toBean(shopJson, Shop.class);
//        }
//        //空字符串表示是我们为了解决缓存穿透而存入的
//        if (Objects.equals(shopJson, "")){
//            return null;
//        }
//        Shop shop = query().eq("id", id).one();
//        if (shop==null){
//            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);//为了解决缓存穿透
//            return null;
//        }
//        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        return shop;
//    }

    //保证数据库和redis的一致性
    @Transactional
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id==null){
            return Result.fail("错误");
        }
       updateById(shop);
       stringRedisTemplate.delete("cache:shop" + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        String key="shop:geo"+typeId;
        if (x==null){
            Page<Shop> shops = query().eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));//current为页码，后面的为每页显示数量
             return Result.ok(shops);
        }
        int from=(current-1)*SystemConstants.MAX_PAGE_SIZE;
        int end=current*SystemConstants.MAX_PAGE_SIZE;
        //查询符合条件的店铺
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key, GeoReference.fromCoordinate(x, y), new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        ArrayList<Long> ids= new ArrayList<>(list.size());
        //保存店铺id和对应店铺的距离
        HashMap<String, Distance> distanceHashMapMap = new HashMap<>();
        //从from开始，from之前的去掉
        if (list.size()<=from){
            return Result.ok();
        }
        Stream<GeoResult<RedisGeoCommands.GeoLocation<String>>> skip = list.stream().skip(from);
        skip.forEach(result->{
            String shopId = result.getContent().getName();
            ids.add(Long.valueOf(shopId));
            Distance distance = result.getDistance();
            distanceHashMapMap.put(shopId,distance);});
            String idsStr = StrUtil.join(",", ids);
            List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
            for (Shop shop:shops) {
                shop.setDistance(distanceHashMapMap.get(shop.getId().toString()).getValue());
            }
       return Result.ok(shops);

}
}
 //
